package com.shenhangye.pushlive.filter

import android.content.Context
import android.opengl.GLES30
import android.opengl.GLES30.glEnableVertexAttribArray

import com.shenhangye.pushlive.opengl.openglutil
import java.nio.FloatBuffer
import java.nio.IntBuffer

open class BaseFilter {

    var vertex_position= floatArrayOf(
        -1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
        1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
        -1.0f, 1.0f, 0.0f,  0.0f, 1.0f,
        1.0f, 1.0f, 0.0f, 1.0f, 1.0f
    )

    var element_position= intArrayOf(
        0,1,2,
        1,2,3
    )
    var vao = intArrayOf(1)
    var vbo = intArrayOf(1)
    var ebo = intArrayOf(1)


    val vertex_buffer: FloatBuffer by lazy{
        openglutil.createFloatBuffer(vertex_position)
    }

    val element: IntBuffer by lazy{
        openglutil.createIntBuffer(element_position)
    }

    var vMatrix=0
    var program=0
    constructor(context: Context,verid:Int,fragId:Int){
        program=openglutil.createProgram(context,verid,fragId);
        vMatrix= GLES30.glGetUniformLocation(program,"vMatrix")
        GLES30.glGenVertexArrays(vao.size,vao,0)
        GLES30.glGenBuffers(vbo.size,vbo,0)
        GLES30.glBindVertexArray(vao[0])
        GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER,vbo[0])
        GLES30.glBufferData(
            GLES30.GL_ARRAY_BUFFER,
            vertex_buffer.capacity() * 4,
            vertex_buffer,
            GLES30.GL_STATIC_DRAW
        )

        vertex_buffer.position(0)
        GLES30.glVertexAttribPointer(0,3,
            GLES30.GL_FLOAT,false,4*5,0)
        glEnableVertexAttribArray(0)

        vertex_buffer.position(3)
        GLES30.glVertexAttribPointer(1,2,
            GLES30.GL_FLOAT,false,4*5,3*4)
        glEnableVertexAttribArray(1)

        GLES30.glGenBuffers(ebo.size,ebo,0)
        GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER,ebo[0])
        GLES30.glBufferData(GLES30.GL_ELEMENT_ARRAY_BUFFER,element.capacity()*4,element, GLES30.GL_STATIC_DRAW)
        GLES30.glBindVertexArray(GLES30.GL_NONE)
        GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, GLES30.GL_NONE)
    }

    var mWidth: Int = 0
    var mHeight: Int = 0
    open fun setSize(width:Int,height:Int){
        mWidth=width;
        mHeight=height;
    }
    open fun beforeDraw() {
    }

    open fun getTextureTarget():Int=GLES30.GL_TEXTURE_2D
    open fun onDraw(texture:Int):Int{
        GLES30.glViewport(0, 0, mWidth, mHeight)
        GLES30.glUseProgram(program)
        GLES30.glBindVertexArray(vao[0])
        GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
        GLES30.glBindTexture(getTextureTarget(), texture)
        beforeDraw()
        GLES30.glDrawElements(GLES30.GL_TRIANGLE_STRIP,6,GLES30.GL_UNSIGNED_INT,0)
        GLES30.glUseProgram (GLES30.GL_NONE);
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D,GLES30.GL_NONE)
        return texture;
    }

    fun release() {
        GLES30.glDeleteProgram(program)
    }
}